<?php

class SlidehomeController extends BackEndController
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    //public $layout='//layouts/column2';
    public $dir_img_tmp_full = "tmp";
    public $dir_img_full = "img/slidehome";
    public $full_width = 430;
    public $full_height = 287;

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }


    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'CropImg', 'Upload','admin', 'delete'),
                'expression'=>'$user->isHaveAccess()',
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    protected function aftersave($filename){
        if (isset($_POST['image_url'])) {
            $image = $this->dir_img_tmp_full.DS;
            $image .= pathinfo($_POST['image_url'], PATHINFO_BASENAME);
            $this->Croping($image,$this->dir_img_full,$filename,$this->full_width,$this->full_height);
            unlink($image);
        }
        $this->redirect(array('slidehome/admin'));
        app()->end();
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new Slidehome;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['Slidehome'])) {
            $model->attributes = $_POST['Slidehome'];
            if ($model->save())
            {
                $this->aftersave($model->id);
            }
        }
        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['Slidehome'])) {
            $model->attributes = $_POST['Slidehome'];
            if ($model->save()) {
                $this->aftersave($model->id);
            }
        }
        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        $this->loadModel($id)->delete();
        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider = new CActiveDataProvider('Slidehome');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new Slidehome('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Slidehome']))
            $model->attributes = $_GET['Slidehome'];
        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function actionCropImg($fm)
    {
        $id = $fm;
        Yii::app()->clientScript->scriptMap = array(
            (YII_DEBUG ? 'jquery.js' : 'jquery.min.js') => false,
        );
        $imageUrl = bu() . '/' . $this->dir_img_tmp_full . '/' . $id;
        $this->renderPartial('cropImg', array('imageUrl' => $imageUrl), false, true);
    }

    protected function Croping($image,$pathThumb,$name,$width,$height)
    {
        if (isset($_POST['cropID'])) {
            if (!file_exists($pathThumb))
                mkdir($pathThumb,0777,true);
            $coords = array(
                'x' => $_POST['AvatarForm_cropX'],
                'y' => $_POST['AvatarForm_cropY'],
                'w' => $_POST['AvatarForm_cropW'],
                'h' => $_POST['AvatarForm_cropH'],
            );
            Yii::import("ext.yii-jcrop.EJCropper");
            $crop = new EJCropper();
            $crop->targ_w = $width;
            $crop->targ_h = $height;
            $crop->thumbPath = $pathThumb;
            $crop->destName = $name;
            $thumb_name = $crop->crop($image, $coords);
            return $thumb_name;
        } else
            return false;
    }

    public function actionUpload()
    {
        $base = app()->basePath;
        Yii::import("ext.EAjaxUpload.qqFileUploader");
        $folder = $this->dir_img_tmp_full . '/'; // folder for uploaded files
        $allowedExtensions = array("jpg", "jpeg", "gif", "png"); //array("jpg","jpeg","gif","exe","mov" and etc...
        $sizeLimit = 1 * 1024 * 1024; // maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder, true);
        $fileSize = filesize($folder . $result['filename']); //GETTING FILE SIZE
        $fileName = $result['filename']; //GETTING FILE NAME
        $result = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        echo $result; // it's array
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Slidehome the loaded model
     * @throws CHttpException
     */
    public function loadModel($id)
    {
        $model = Slidehome::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Slidehome $model the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'slidehome-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
